<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

class AutogeneratorControllerTable extends JControllerForm {

    /**
     *
     * @var AutogeneratorModelComponent 
     */
    public $oModelComponent;
    /**
     *
     * @var AutogeneratorModelField 
     */
    public $oModelField;

    /**
     *
     * @var AutogeneratorModelTable 
     */
    public $oModelTable;
    /**
     *
     * @var AutogeneratorModelMvc 
     */
    public $oModelMVC;
    public $oApplication;

    public function __construct($config = array()) {
        parent::__construct($config);

        $this->oModelTable = $this->getModel();
        $this->oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $this->oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        $this->oModelMVC = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $this->oApplication = JFactory::getApplication();
    }

    public function checkTitleValid($sTitle) {
        $sRegex = '/^[A-Za-z0-9_]+$/';

        if (!preg_match($sRegex, $sTitle))
            return false;

        return true;
    }

    public function checkDuplicateTitle($iTableId, $sTitle) {
        $oTable = $this->oModelTable->getItem($iTableId);

        if (intval($oTable->id) == 0)
            return true;

        $iComponentId = intval($oTable->component_id);

        if ($iComponentId > 0) {
            $aTables = AutogeneratorHelper::getAllTablesByComponentId($iComponentId);

            foreach ($aTables as $oTable) {
                if ($oTable->id == $iTableId)
                    continue;

                if (JString::strcmp($oTable->title, $sTitle) == 0)
                    return false;
            }
        }

        return true;
    }

    public function editInline() {
        $aData = $this->oApplication->input->get('data', array(), 'array');

        if (!$this->checkTitleValid($aData['custom'])) {
            echo JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_TITLE_NOT_VALID');
            die;
        }

        // Trim text.
        $aData['custom'] = trim($aData['custom']);

        if ($aData['custom'] == '') {
            echo JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_TITLE_BLANK');
            die;
        }

        $iFirstChar = ord($aData['custom'][0]);
        // Check in [A - z].
        if (ord('A') > $iFirstChar || $iFirstChar > ord('z')) {
            echo JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_TITLE_FIRST_CHAR_NOT_VALID');
            die;
        }

        // Check duplicate title.
        if (!$this->checkDuplicateTitle($aData['id'], $aData['custom'])) {
            echo JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_TITLE_DUPLICATE');
            die;
        }

        $aValue = array(
            'id' => $aData['id'],
            'title' => $aData['custom']
        );

        if (!$this->oModelTable->editInline($aValue)) {
            echo JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $this->oModelTable->getError());
        }
        echo 1;

        die;
    }

    public function importFields() {
        $iTableId = $this->oApplication->input->getInt('iTableId');

        // Delete all old fields that exist table.
        $sMessage = $this->oModelTable->deleteAllFields($iTableId);

        if ($sMessage !== true) {
            echo $sMessage;
            die;
        }

        // Get all fields of the table.
        $aFields = $this->oModelTable->getAllFieldsInDatabaseByTableId($iTableId);

        // Total fields added.
        $iTotal = 0;
        $aFieldIds = array();
        foreach ($aFields as $iKey => $oField) {
            $aField = array(
                'table_id' => $iTableId,
                'sql_field' => $oField->Field,
                'sql_type' => $oField->Type,
                'sql_null' => $oField->Null,
                'sql_key' => $oField->Key,
                'sql_default' => $oField->Default,
                'sql_extra' => $oField->Extra,
                'allow_edit_in_list' => 0,
                'ordering' => $iKey + 1
            );

            $bResult = $this->oModelTable->storeField($aField);

            if ($bResult == false) {
                echo 0;
                die;
            }
            
            $iTotal++;
        }
        
        $this->importMVC($iTableId);
        
        echo $iTotal;
        die;
    }
    
    public function importMVC($iTableId)
    {
        // Delete all old MVCs that exist in table.
        $sMessage = $this->oModelMVC->deleteAllMVC($iTableId);

        if ($sMessage !== true) {
            echo $sMessage;
            die;
        }

        // Get drap MVCs of the table.
        $aMVCs = $this->oModelMVC->getDrapMVC($iTableId);

        foreach ($aMVCs as $aMVC) {
            $this->oModelMVC->storeTable($aMVC);
        }
    }

    public function changeStatus() {
        $iTableId = $this->oApplication->input->getInt('iTableId');

        // Get table.
        $sMessage = $this->oModelTable->changeStatus($iTableId);

        echo $sMessage;
        die;
    }

    public function exportPHPFile() {
        $sFileName = 'table.php';
        
        $iTableId = $this->oApplication->input->getInt('iTableId');
        $oTable = $this->getModel()->getItem($iTableId);
        if ($oTable)
        {
            $sFileName = strtolower($oTable->title) . '.php';
        }
        $sContent = AutogeneratorHelper::getTableContent($iTableId);

        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$sFileName");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");

        echo $sContent;
        die;
    }

    public function importForMultiTables() {
        $aTableId = $this->oApplication->input->get('cid', array(), 'array');

        foreach ($aTableId as $iTableId) {
            // Delete all old fields that exist table.
            $sMessage = $this->oModelTable->deleteAllFields($iTableId);

            if ($sMessage !== true) {
                $this->oApplication->redirect(JRoute::_('index.php?option=com_autogenerator&view=tables', false), $sMessage);
            }

            // Get all fields of the table.
            $aFields = $this->oModelTable->getAllFieldsInDatabaseByTableId($iTableId);

            foreach ($aFields as $iKey => $oField) {
                $aField = array(
                    'table_id' => $iTableId,
                    'sql_field' => $oField->Field,
                    'sql_type' => $oField->Type,
                    'sql_null' => $oField->Null,
                    'sql_key' => $oField->Key,
                    'sql_default' => $oField->Default,
                    'sql_extra' => $oField->Extra,
                    'allow_edit_in_list' => 0,
                    'ordering' => $iKey + 1
                );
                $bResult = $this->oModelTable->storeField($aField);

                if ($bResult == false) {
                    $this->oApplication->redirect(JRoute::_('index.php?option=com_autogenerator&view=tables', false), JText::_('COM_AUTOGENERATOR_IMPORT_TABLE_IMPORT_SELECTED_TABLE_FAILURE'));
                }
                
                $this->importMVC($iTableId);
            }
        }

        $this->oApplication->redirect(JRoute::_('index.php?option=com_autogenerator&view=tables', false), JText::_('COM_AUTOGENERATOR_IMPORT_TABLE_IMPORT_SELECTED_TABLE_SUCCESS'));
    }
}
